using System;
using System.Text;
using System.Linq;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;

namespace $safeprojectname$.Features.Install
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("$Guid_FeatureRecieverClass_Automation_Install$")]
    public class InstallEventReceiver : SPFeatureReceiver
    {
        readonly Guid _webPublishingGuid = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"); // OOTB Web Publishing Feature

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (var siteCollection = (SPSite)properties.Feature.Parent)
            {
                if (siteCollection != null)
                {
                    // Enumerate through each site and apply branding.
                    foreach (SPWeb web in siteCollection.AllWebs)
                    {
                        ConfigureMasterPagesAndLogo(web, false);

                        web.Dispose();
                    }
                }
            }
        }


        // The method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            #region Restore the master pages, logo, and CSS on each site in the collection
            try
            {
                using (var siteCollection = (SPSite)properties.Feature.Parent)
                {
                    // Enumerate through each site and apply branding.
                    foreach (SPWeb web in siteCollection.AllWebs)
                    {
                        ConfigureMasterPagesAndLogo(web, true);

                        web.Dispose();
                    }
                }
            }
            catch { }
            #endregion
        }

        /// <summary>
        /// Updates the master pages and site logo on the specified SharePoint web to use the custom 
        /// branding elements included in this solution. This function can also be used to restore
        /// the default master pages and reset the logo.
        /// </summary>
        /// <param name="web">A reference to the SharePoint web to be branded</param>
        /// <param name="restoreDefaults">If set to TRUE then this function will return the default master pages for the selected web.</param>
        private void ConfigureMasterPagesAndLogo(SPWeb web, bool restoreDefaults)
        {
            // Format the web app relative URL of the site collection so that it always ends with a "/"
            // This helps with site collections that are below the root (e.g. "/sites/searchcenter")
            string relativeUrlOfSiteCollection = web.Site.RootWeb.ServerRelativeUrl;
            if (!relativeUrlOfSiteCollection.EndsWith("/"))
            {
                relativeUrlOfSiteCollection += "/";
            }

            // Configure the appropriate branding based on the site template
            switch (web.WebTemplate)
            {
                // Publishing Sites
                case "BLANKINTERNET":
                case "CMSPUBLISHING":

                    if (restoreDefaults == true)
                    {
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.SiteLogoUrl = "";
                    }
                    else
                    {
                        // Set the master pages and site logo
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/Site_DefaultChannel.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/System.master";
                        web.SiteLogoUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/Images/logo.png";
                    }

                    break;

                // Search Center
                case "SRCHCEN":

                    if (restoreDefaults == true)
                    {
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.SiteLogoUrl = "";
                    }
                    else
                    {
                        // Set the master pages and site logo
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/System.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/System.master";
                        web.SiteLogoUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/Images/logo.png";
                    }

                    break;

                // App Sites
                case "App":
                case "AppCatalog":

                    // Do Nothing

                    break;

                // All other templates (Team Sites and other collaboration sites)
                default:

                    if (restoreDefaults == true)
                    {
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/seattle.master";
                        web.SiteLogoUrl = "";
                    }
                    else
                    {
                        // Set the master pages and site logo
                        web.CustomMasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/System.master";
                        web.MasterUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/MasterPages/System.master";
                        web.SiteLogoUrl = relativeUrlOfSiteCollection + "_catalogs/masterpage/$clientNameWithoutSpaces$/Images/logo.png";
                    }

                    break;
            }

            // Check to see if the web level SharePoint Publishing Feature is enabled, 
            // if so, set sub sites to inherit their masterpage settings from the rootweb
            if (web.Features[_webPublishingGuid] != null)
            {
                if (web.Url == web.Site.Url)
                {
                    web.AllProperties["__InheritsCustomMasterUrl"] = "FALSE";
                    web.AllProperties["__InheritsMasterUrl"] = "FALSE";
                }
                else
                {
                    web.AllProperties["__InheritsCustomMasterUrl"] = "TRUE";
                    web.AllProperties["__InheritsMasterUrl"] = "TRUE";
                }
            }

            // Update the web to commit the changes
            web.Update();
        }


        #region Unused Event Receiver Overrides
        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
        #endregion

    }
}